package com.ruoyi.quartz.task;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.ContractConfigDay;
import com.ruoyi.system.domain.ContractExpire;
import com.ruoyi.system.domain.ContractPlanAmount;
import com.ruoyi.system.service.IContractConfigDayService;
import com.ruoyi.system.service.IContractExpireService;
import com.ruoyi.system.service.IContractPlanAmountService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 账款计划到期时间
 */
@Component("contractExpireTask")
public class ContractExpireTask {
    @Autowired
    private IContractPlanAmountService iContractPlanAmountService;
    @Autowired
    private IContractExpireService iContractExpireService;

    @Autowired
    private IContractConfigDayService contractConfigDayService;

    public void excute() {
        List<ContractConfigDay> days = contractConfigDayService.selectContractConfigDayList(new ContractConfigDay());
        List<ContractPlanAmount> amountList = iContractPlanAmountService.selectContractPlanAmountList(new ContractPlanAmount());
        //清空数据
        iContractExpireService.deleteContractExpireAll();
        for (ContractPlanAmount amount : amountList) {
            Date planDate = amount.getPlanDate();

            long day = DateUtils.dayDistance(planDate, DateUtils.getNowDate());
            //提前七天通知
            Integer num = 7;
            if(CollectionUtils.isNotEmpty(days)){
                num = days.get(0).getDayNum();
            }
            //提前七天通知
            if (day <= num) {

                ContractExpire contractExpire = iContractExpireService.selectContractExpireByPlanId(amount.getId());
                if (contractExpire == null) {
                    //新增
                    ContractExpire  expire = new ContractExpire();
                    expire.setPlanId(amount.getId());
                    expire.setLastDay(day);
                    iContractExpireService.insertContractExpire(expire);
                } else {
                    //修改
                    contractExpire.setLastDay(day);
                    iContractExpireService.updateContractExpire(contractExpire);
                }

            }
        }
    }

}
